package com.example.shop_2302.fg

import android.content.Context
import android.os.Bundle
import android.os.Handler
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.example.base.entity.Roll
import com.example.base.mvvm.BaseFragment
import com.example.shop_2302.R
import com.example.shop_2302.adapter.GoodsAdapter
import com.example.shop_2302.adapter.MenuAdapter
import com.example.shop_2302.adapter.MoneyAdapter
import com.example.shop_2302.adapter.NewsAdapter
import com.example.shop_2302.adapter.QuanAdapter
import com.example.shop_2302.databinding.FragmentHomeBinding
import com.example.shop_2302.utils.GlideUtils
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.youth.banner.loader.ImageLoader
import java.util.Timer
import java.util.TimerTask


class HomeFragment : BaseFragment<FragmentHomeBinding,HomeViewModel>() {
    val imgs = mutableListOf<String>()//存放轮播图图片的集合
    lateinit var menuAdapter: MenuAdapter
    lateinit var newsAdapter: NewsAdapter
    //定义定时器，让新闻内容可滚动起来
    lateinit var timer:Timer
    val handler = Handler()
    var postion = 0//新闻列表的下标

    lateinit var moneyAdapter: MoneyAdapter

    lateinit var goodsAdapter: GoodsAdapter
    var type = 4//当前分类  默认为4
    var page = 1//当前页面 默认为1

    lateinit var quanAdapter: QuanAdapter
    override fun initView() {
        //请求数据
        viewModel.index()
        //初始化菜单
        menuAdapter = MenuAdapter()
        binding.rvMenu.adapter = menuAdapter
        binding.rvMenu.layoutManager = GridLayoutManager(context,5)
        //初始化新闻
        newsAdapter = NewsAdapter()
        binding.rvNews.adapter = newsAdapter
        binding.rvNews.layoutManager = LinearLayoutManager(context)
        //初始化省钱分类
        moneyAdapter = MoneyAdapter()
        binding.rvMoney.adapter = moneyAdapter
        binding.rvMoney.layoutManager = GridLayoutManager(context,4)

        //开启定时任务，让数据进行滚动
        timer = Timer()
        timer.schedule(object:TimerTask(){
            override fun run() {
                handler.post {
                    binding.rvNews.scrollToPosition(postion)
                    postion++
                    if(postion==newsAdapter.data.size){
                        postion = 0
                    }
                }
            }
        },0,2000)
        //初始化商品列表
        goodsAdapter = GoodsAdapter()
        binding.rvGoods.adapter = goodsAdapter
        binding.rvGoods.layoutManager = GridLayoutManager(context,2)
        //请求商品
        viewModel.indexGoods(type,5,page)
        //点击分类。下方数据进行变化，同时选中的分类的文字颜色变为红色
        moneyAdapter.setOnItemClickListener { adapter, view, position ->
            type = moneyAdapter.data[position].type.toInt()
            moneyAdapter.updateType(type)
            //每次点击分类时，查看的数据一定是第一页的
            page = 1
            viewModel.indexGoods(type,5,page)
        }
        //刷新框架///////点击分类时，一定给type和page进行重新赋值  不然数据不准确
        binding.smart.setOnRefreshLoadMoreListener(object :OnRefreshLoadMoreListener{
            override fun onRefresh(refreshLayout: RefreshLayout) {
                page = 1
                viewModel.indexGoods(type,5,page)
                binding.smart.finishRefresh()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                viewModel.indexGoods(type,5,++page)
                binding.smart.finishLoadMore()
            }
        })
        //点击搜索框，跳转到搜索界面
        binding.clSearch.setOnClickListener {
            ARouter.getInstance().build("/app/SearchActivity").navigation()
        }
        //初始化优惠券
        quanAdapter = QuanAdapter()
        binding.rvQuan.adapter = quanAdapter
        binding.rvQuan.layoutManager = LinearLayoutManager(context,LinearLayoutManager.HORIZONTAL,false)//横向滑动
        //请求优惠券
        viewModel.quan("10","1","1")
        //点击事件，实现领取优惠券//点击领取控件，实现领取
        quanAdapter.addChildClickViewIds(R.id.quan_status)
        quanAdapter.setOnItemChildClickListener { adapter, view, position ->
            when(view.id){
                R.id.quan_status->{
                    if(quanAdapter.data[position].isUse){
                        ToastUtils.showLong("已经领取了，不能重复领取")
                    }else{
                        //后台实现领取
                        viewModel.quanReceive(quanAdapter.data[position].id)
                        //页面发生变化
                        quanAdapter.data[position].isUse = true
                        quanAdapter.notifyDataSetChanged()
                    }
                }
            }
        }

        //点击菜单中的第8个（下标为7），跳转到地址列表界面
        menuAdapter.setOnItemClickListener { adapter, view, position ->
            when(position){
                7->{
                    ARouter.getInstance().build("/app/AddressActivity").navigation()
                }
            }

        }

        //点击商品item，跳转到详情界面

        goodsAdapter.setOnItemClickListener { adapter, view, position ->
            ARouter.getInstance().build("/app/XqActivity").withInt("goodsId",goodsAdapter.data[position].id).navigation()
        }

    }

    override fun initData() {
        viewModel.indexSuccess.observe(this){
            if(it.code==200){
                //展示对应数据
                //展示轮播图
                it.data.banner.forEach {
                    imgs.add(it.pic)
                }
                binding.banner.setImages(imgs)
                    .setImageLoader(object:ImageLoader(){
                        override fun displayImage(
                            context: Context?,
                            path: Any?,
                            imageView: ImageView?
                        ) {
                            if (context != null) {
                                if (imageView != null) {
                                    GlideUtils.loadNormal(context, path.toString(),imageView)
                                }
                            }
                        }
                    }).start()
                //显示菜单
                menuAdapter.data.clear()
                menuAdapter.data.addAll(it.data.menus)
                menuAdapter.notifyDataSetChanged()
                //显示新闻列表
                newsAdapter.data.clear()
                newsAdapter.data.addAll(it.data.roll)
                newsAdapter.data.add(Roll(123,"新品限量抢，积分帆两倍","",""))
                newsAdapter.notifyDataSetChanged()
                //显示分类
                moneyAdapter.data.clear()
                moneyAdapter.data.addAll(it.data.explosiveMoney)
                moneyAdapter.notifyDataSetChanged()
            }else{
                ToastUtils.showLong(it.message)
            }
        }

        viewModel.goodsSuccess.observe(this){
            if(it.code==200){
                if(page==1){
                    goodsAdapter.data.clear()
                }
                goodsAdapter.data.addAll(it.data.list)
                goodsAdapter.notifyDataSetChanged()
                //当没有请求到数据时，给出提示
                if(it.data.list.isEmpty()){
                    ToastUtils.showLong("没有加载到更多数据")
                }
            }else{
                ToastUtils.showLong(it.message)
            }
        }
        viewModel.quanSuccess.observe(this){
            if(it.code==200){
                quanAdapter.data.clear()
                quanAdapter.data.addAll(it.data)
                quanAdapter.notifyDataSetChanged()
            }else{
                ToastUtils.showLong(it.message)
            }
        }
        viewModel.quanFail.observe(this){
            ToastUtils.showLong(it)
        }
        viewModel.recevieSuccess.observe(this){
            ToastUtils.showLong(it.message)
        }
        viewModel.receiveFail.observe(this){
            ToastUtils.showLong(it)
        }
    }

    override fun getViewModel(): Class<HomeViewModel> = HomeViewModel::class.java

    override fun getLayout(): Int = R.layout.fragment_home

}